<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Order as OrderService;
use app\common\service\Material as MaterialService;
use app\common\service\TTask as TTaskService;
use app\common\service\TTaskLog as TTaskLogService;
use app\common\service\TTaskAttention as TTaskAttentionService;
use app\common\service\TTaskRights as TTaskRightsService;
use app\common\service\TProject as TProjectService;
use \app\common\service\SystemUser as SystemUserService;
/**
 * 任务管理
 * @author King
 *
 */
class TTask extends Admin
{
	protected $hisiValidate = 'TTask';

    public function initialize() {
    	parent::initialize();

    	$projectKV = (new TProjectService())->getList(null);
    	$this->assign('projectKV', $projectKV);
    }

    /**
     * 任务列表
     *
     * @author King
     * @date 2020年8月21日
     *
     * @return string
     */
    public function index()
    {
		if ($this->request->isAjax()) {
			$projectId = $this->request->param('project_id/d', 0);
			$type = $this->request->param('type/d', 0);	// 0全部，1我创建，2我参与，3我关注
			$order = $this->request->param('order/s', 'create_time');	// 优先级，创建时间，更新时间
            $keywords=$this->request->param('keywords','');
            $systemUserKV = getSystemUserKV(null);
			$result = [];
			$where = [];
            $order='create_time';
			$whereJoin = "1=1";
			if ($projectId) $where[] = ['project_id', '=', $projectId];
			//if ($type == 1) $where[] = ['admin_id', '=', ADMIN_ID];
            $whereOR='';
            if(!empty($keywords)){
                $whereOR="name like '%{$keywords}%' or client_ordernum like '%{$keywords}%' ";
            }
			if ($type == 1) { //与我相关的  -->  待我审批,由我创建,由我协助,由我执行的任务
                $whereOR= 'audit_uid ='.ADMIN_ID.' or admin_id ='.ADMIN_ID.' or execute_uid ='.ADMIN_ID." or FIND_IN_SET(".ADMIN_ID.", join_admin_ids)";
			}
			elseif ($type == 3) $where[] = ['id', 'in', db('t_task_attention')->where('admin_id', ADMIN_ID)->column('task_id')];

			$field = "id,name,client_ordernum,material_id,material_sku,priority,create_time,update_time,admin_id,execute_uid,project_id,audit_status,status,task_label";

			$result['todoNum'] = db('t_task')->where($whereOR)->where($where)->whereRaw($whereJoin)->where([['status','<=', 1]])->count(1);
			$result['todoList'] = db('t_task')->where($whereOR)->where($where)->whereRaw($whereJoin)->where([['status','<=', 1]])->field($field)->order($order, 'desc')->select();

			$result['doingNum'] = db('t_task')->where($whereOR)->where($where)->whereRaw($whereJoin)->where('status', 2)->count(1);
			$result['doingList'] = db('t_task')->where($whereOR)->where($where)->whereRaw($whereJoin)->where('status', 2)->field($field)->order($order, 'desc')->select();

			$result['doneNum'] = db('t_task')->where($whereOR)->where($where)->whereRaw($whereJoin)->where('status', 3)->count(1);
			$result['doneList'] = db('t_task')->where($whereOR)->where($where)->whereRaw($whereJoin)->where('status', 3)->field($field)->order("create_time", 'desc')->limit(50)->select();

			$result['pauseNum'] = db('t_task')->where($whereOR)->where($where)->whereRaw($whereJoin)->where('status', 4)->count(1);
			$result['pauseList'] = db('t_task')->where($whereOR)->where($where)->whereRaw($whereJoin)->where('status', 4)->field($field)->order($order, 'desc')->select();
            $project_names=db("t_project")->column('name,id','id');
            $project_audits=[];
            foreach ($project_names as $pid=>$pro_name){
                $project_audits[$pid]=db('t_project_user pu')->where([['project_id','eq',$pid],['type','eq',1]])
                    ->join('system_user suser',"pu.admin_id=suser.id")->column('nick');
                $project_audits[$pid]=count($project_audits[$pid])>0 ? implode(',',$project_audits[$pid]) : $project_audits[$pid];
            }
			$tTaskService = new TTaskService();
			$tTaskRightsService = new TTaskRightsService();
			$allKeyList = ['todoList', 'doingList', 'doneList', 'pauseList'];
			foreach ($allKeyList as $val) {
				foreach ($result[$val] as $k => &$v) {
					$taskId = $v['id'];
                    $v['admin_user']=arrayGet($systemUserKV,$v['admin_id'],'');
                    $v['execute_user']=arrayGet($systemUserKV,$v['execute_uid'],'');
                    $v['project_name']=isset($project_names[$v['project_id']]) ? $project_names[$v['project_id']] : '' ;
                    $v['audit_users']=$project_audits[$v['project_id']];
					$result[$val][$k]['progressLastAdminInfo'] = $tTaskService->getProgressLastAdminInfo($taskId);

					$roleId = $tTaskRightsService->getTaskRoleId($taskId);

					// 是否可修改状态
					$result[$val][$k]['canChangeStatus'] =1;// $tTaskRightsService->checkCanChangeStatus($taskId, $roleId);

					// 是否可关注
					$result[$val][$k]['canAttention'] =1;// $tTaskRightsService->checkCanAttention($taskId, $roleId);

					// 是否可编辑
					$result[$val][$k]['canEdit'] = 1;// $tTaskRightsService->checkCanEdit($taskId, $roleId);

					// 是否可删除
					$result[$val][$k]['canDel'] = $tTaskRightsService->checkCanDel($taskId, $roleId);

					// 是否已关注
					$result[$val][$k]['isAttention'] = $tTaskService->checkIsAttention($taskId);

					// 获取评论数
					$result[$val][$k]['commentNum'] = $tTaskService->getCommentNum($taskId);

				}
			}

			return $this->Json(1, '', $result);
		}
        $projectKV = (new TProjectService())->getList(null);
        $assign['projectKV']=$projectKV;
    	return $this->assign($assign)->fetch();
    }

    /**
     * 任务详情
     */
    public function detail() {
    	$taskId = $this->request->param('id/d', 0);
		$systemUserService=new SystemUserService();
		$systemUserKV = getSystemUserKV(null);
    	$tProjectService = new TProjectService();
    	$tTaskService = new TTaskService();
    	$tTaskRightsService = new TTaskRightsService();
		$tTaskLogService = new TTaskLogService();
		$materialService = new MaterialService();
    	$ttInfo = $tTaskService->getInfoById($taskId);		
		$systemUserVK = $systemUserService->getVKList(null);
		$page       = $this->request->param('page/d', 1);
		$limit      = $this->request->param('limit/d', 5);
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}
		$materialInfo=$materialService->getInfoBySku($ttInfo['material_sku']);
		if(empty($materialInfo)){
			$materialInfo=[
				'name'=>'',
				'color'=>'',
			];
		}
    	$rightsInfo = [];
    	$roleId = $tTaskRightsService->getTaskRoleId($taskId);
    	// 是否可修改状态
    	$rightsInfo['canChangeStatus'] = 1;//$tTaskRightsService->checkCanChangeStatus($taskId, $roleId);
    	// 是否可修改进度
    	$rightsInfo['canChangeProgress'] =1;// $tTaskRightsService->checkCanChangeProgress($taskId, $roleId);
    	// 是否可编辑
    	$rightsInfo['canEdit'] =1; //$tTaskRightsService->checkCanEdit($taskId, $roleId);
    	// 是否可删除
    	$rightsInfo['canDel'] = $tTaskRightsService->checkCanDel($taskId, $roleId);
    	// 是否可发布评论
    	$rightsInfo['canCommentCreate'] =1;// $tTaskRightsService->checkCommentCreate($taskId, $roleId);
		//获取评论
		$rightsInfo['comment']=db('t_task_comment')->where('task_id', $taskId)->order('update_time desc')->where('status', 1)->select();
		foreach ($rightsInfo['comment'] as $key => $value) {
			$a=str_replace('&lt;','<',$value['content']);
			$b=str_replace('&gt;','>',$a);
			$c=str_replace('&quot;','"',$b);
			$d=str_replace('nbsp;','',$c);
			$e=str_replace('&amp;',' ',$d);
			$rightsInfo['comment'][$key]['content']=$e;
			$rightsInfo['comment'][$key]['nick']= arrayGet($systemUserKV, $rightsInfo['comment'][$key]['admin_id'],'');	
		}
    	// 获取评论数
    	$rightsInfo['commentNum'] = $tTaskService->getCommentNum($taskId);
        $ttInfo['execute_user']=arrayGet($systemUserKV,$ttInfo['execute_uid'],'');
        $ttInfo['join_admins']=!empty($ttInfo['join_admin_ids']) ? $this->_getIdstrNames($ttInfo['join_admin_ids'],$systemUserKV) : '';
    	$assign = [
			'materialInfo'=>$materialInfo,
    		'ttInfo' => $ttInfo,
    		'rightsInfo' => $rightsInfo,
    		'creator' => arrayGet($systemUserKV, $ttInfo['admin_id'], ''),
    		'projectUserList' => $tProjectService->getUsersByProjectId($ttInfo['project_id'], [1,2,3]),
    		'progressList' => $tTaskService->getProgressList($taskId),
			'systemUserKV'=>$systemUserKV
    	];
    	$assign['loglist']=$this->getTaskLogList($taskId);
    	return $this->assign($assign)->fetch();
    }

    /**
     * sparkguo
     * 任务新增/编辑功能
     */
    public function taskEdit(){
        $taskId= $this->request->param('task_id/d', 0);
        $projectId = $this->request->param('project_id/d', 0);
        $name = $this->request->param('name/s', '');
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $materialSku = $this->request->param('material_sku/s', 'from_pc');
        $content = $this->request->param('content/s', '');
        $priority = $this->request->param('priority/d', 2);
        $execute_uid = $this->request->param('execute_uid/d');
        $join_admin_ids = $this->request->param('join_admin_ids/s');
        $orderQuantity = $this->request->param('order_quantity/d',0);
        $real_order_quantity = $this->request->param('real_order_quantity/d', '');
        $real_process_price = $this->request->param('real_process_price/s', '');
        $process_price=$this->request->param('process_price/f','');
        $notic_open = $this->request->param('notice_open/d','');
        $material_ids=$this->request->param("material_ids/s",'');
        $action=$this->request->param('action/s');
        if($action=='changeExecuteUid'){
           return $this->_changeExecuteUser();
        }
        if($action=='getOrderMaterials'){
            return $this->_getOrderMaterials();
        }
        if($action=='addTaskLabel'){ //任务增加标签
            return $this->_addTaskLabel();
        }

        if ($this->request->isAjax()) {
            $systemUserKV = getSystemUserKV(null);
            if (empty($name) || empty($execute_uid) || empty($projectId)) {
                $this->return_json('401', '项目id或任务名称或执行人参数缺失');
            }

            try {
                db()->startTrans();
                $insData = [
                    'project_id' => $projectId,
                    'name' => $name,
                    'client_ordernum' => $clientOrdernum,
                    'material_sku' => $materialSku,
                    'material_id'=>$material_ids,
                    'content' => $content,
                    'execute_uid' => $execute_uid,
                    'priority' => $priority,
                    'admin_id' => ADMIN_ID,
                    'join_admin_ids' => $join_admin_ids,
                    'order_quantity' => $orderQuantity,
                    'process_price' => $process_price,
                    'real_order_quantity' => $real_order_quantity,
                    'real_process_price' => $real_process_price,
                    'status' => 0,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                $audit_uid = db('t_project_user')->where(['project_id' => $projectId, 'type' => 1])->value('admin_id', '0');//审批人
                if ($notic_open == 2) {
                    $insData['close_notice_uid'] = ADMIN_ID;
                }
                if (empty($taskId)) {
                    $insData['audit_uid'] = $audit_uid;
                    $taskId = db('t_task')->insertGetId($insData);
                    // 记录操作日志
                    $this->addLog($projectId, $taskId, 3, '新建了任务', 0);
                } else {
                    unset($insData['create_time']);
                    unset($insData['admin_id']);
                    unset($insData['status']);
                    $oldtaskinfo = db('t_task')->find($taskId);
                    db('t_task')->where('id', $taskId)->update($insData);
                    if ($oldtaskinfo['name'] != $name) {
                        $content="原标题：". $oldtaskinfo['name'];
                        $this->addLog($projectId, $taskId, 1, '更新了任务标题', 0, $name,$content);
                    }
                    if ($oldtaskinfo['content'] != $content) {
                        $this->addLog($projectId, $taskId, 1, '更新了任务描述', 0, '原描述：'.$oldtaskinfo['content']);
                    }
                    if ($oldtaskinfo['priority'] != $priority) {
                        $this->addLog($projectId, $taskId, 1, '更新了任务 重要性' . $oldtaskinfo['priority'] . '->' . $priority, 0);
                    }
                    if ($oldtaskinfo['execute_uid'] != $execute_uid) {
                        $oldExeName = arrayGet($systemUserKV, $oldtaskinfo['execute_uid'], '');
                        $newExeName = arrayGet($systemUserKV, $execute_uid, '');
                        $this->addLog($projectId, $taskId, 1, '将任务指派给' . $newExeName . '，原指派人： ' . $oldExeName, 0);
                    }
                }
                db()->commit();
                $retData['task_id'] = $taskId;
                return $this->Json(1);
            } catch (\Exception $e) {
                db()->rollback();
                $this->return_json(501, "操作失败，" . $e->getMessage() . $e->getLine());
            }
        }
        $systemUserKV = getSystemUserKV(null);
        $tProjectService = new TProjectService();
        $taskinfo=$taskId > 0 ? db("t_task")->find($taskId) :['name'=>'','join_admin_ids'=>'','content'=>'','client_ordernum'=>'','priority'=>'','id'=>'','material_id'=>''];
        $taskJoinUsers=$taskinfo['join_admin_ids']!='' ? explode(',',$taskinfo['join_admin_ids']) : [];
        $taskinfo['project_id']=!empty($taskinfo['project_id']) ? $taskinfo['project_id'] : $projectId;
        $taskinfo['project_id']=!empty($taskinfo['project_id']) ? $taskinfo['project_id'] : db("t_project")->where([['status','<',99]])->order("id asc")->value('id');//未选项目点新增任务
        $projectUser= $tProjectService->getUsersByProjectId($taskinfo['project_id'], [1,2,3]);
        //所有项目的执行人与协助人列表
        $result=db('t_project_user')->field('distinct project_id,admin_id')->select();
        $allProUsers =$doubleSelects= [];
        foreach ($result as $proUser) {
            $adminId=$proUser['admin_id'];
            $proid=$proUser['project_id'];
            $allProUsers[$proid][$adminId] = arrayGet($systemUserKV, $adminId, '');
            $otherUser=['name'=>arrayGet($systemUserKV, $adminId, ''),'value'=>$adminId];
            $doubleSelects[$proid][]=$otherUser;
        }
        $assign= [
            'task'=>$taskinfo,
            'projectUserList' => $projectUser,
            'allProUsers'=>$allProUsers,
            'doubleSelects'=>$doubleSelects
        ];
        foreach ($projectUser as $key => $value) {
            $otherUser=['name'=>$value,'value'=>$key];
            if(is_array($taskJoinUsers) && in_array($key,$taskJoinUsers)){
                $otherUser['selected']=true;
            }
            $assign['taskJoinUsers'][]=$otherUser;
        }
        return $this->assign($assign)->fetch('form');
    }

    private function _changeExecuteUser(){
        $taskId = $this->request->param('id/d', 0);
        $execute_uid = $this->request->param('admin_id/d', 0);
        $assistAdminIds = $this->request->param('assist_admin_ids/a', []);
        $remark = $this->request->param('remark/s', '');
        $remark=$remark!=''? "附言：".$remark : '';
        $systemUserKV = getSystemUserKV(null);
        $oldtaskinfo = db('t_task')->find($taskId);
        db('t_task')->where('id', $taskId)->update(['execute_uid'=>$execute_uid]);
        if ($oldtaskinfo['execute_uid'] != $execute_uid) {
            $oldExeName = arrayGet($systemUserKV, $oldtaskinfo['execute_uid'], '');
            $newExeName = arrayGet($systemUserKV, $execute_uid, '');
            $this->addLog($oldtaskinfo['project_id'], $taskId, 1, '将任务指派给' . $newExeName . '，原指派人：' . $oldExeName, 0,$remark);
        }
        return $this->Json(1,'处理成功');
    }

    private function _getOrderMaterials(){
        $orderNumbers = $this->request->param('order_number/s', '');
        $orderNumbers=trim($orderNumbers);
        $orderNumbers=explode(',',str_replace(["，",'/'],",",$orderNumbers));
        $result=db('order_material om')->join('material m', "om.material_id=m.id", 'left')
            ->where([['client_ordernum','in',$orderNumbers]])->field('om.mid,om.material_id,om.order_id,om.client_ordernum,om.fabric_width,om.weight
                ,om.material_dosage,om.loss,om.caigou_status,om.factory_id
                ,om.is_make_tag,om.is_caigou_start,om.need_checkcloth,om.need_shrink
                ,om.caigou_unitprice,om.shiji_caigou_count,om.tiaoshu,om.tiaoshu_detail,om.tiaoshu_status,om.return_length
                ,om.arrive_time,om.arrive_time_first,om.caigou_over_time
                ,om.send_goods_status,om.create_time,om.need_num
                ,m.pic,m.name,m.type,m.material_sku,m.model,m.colornum,m.color,m.supplier,m.address,m.contact
                ,m.purchasing_unit')->select();
        $retdata=[];$optionStr='<option value="0">请选择</option>';
        foreach($result as $key=>$item){
            $materialtype=$item['type']=='accessories' ? '[辅]' : '[面]';
            $optionStr.="<option value='$item[mid]' data-client_ordernum='$item[client_ordernum]' data-name='名称:$item[name],供应商:$item[supplier],颜色:$item[color],色号:$item[colornum],型号:$item[model]' data-supplier='$item[supplier]'>$materialtype$item[name]</option>";
        }
        return $this->Json(1,'处理成功',['optionstr'=>$optionStr]);
    }

    private function _addTaskLabel(){
        $taskId = $this->request->param('id/d', 0);
        $labelName = $this->request->param('label_name/s', '');
        $systemUserKV = getSystemUserKV(null);
        $oldtaskinfo = db('t_task')->find($taskId);
        $oldtaskinfo['task_label']=trim($oldtaskinfo['task_label']);
        if (stripos($oldtaskinfo['task_label'],$labelName)===false) {
            db('t_task')->where('id', $taskId)->update(['task_label'=>$oldtaskinfo['task_label']." ".$labelName]);
            $this->addLog($oldtaskinfo['project_id'], $taskId, 3, '增加标签：' . $labelName );
        }
        return $this->Json(1,'处理成功');
    }



    /**
     *增加任务日志
     * @logType //1任务修改 2评论, 3改变进度/完成状态等
     */
    public function addLog($projectId,$taskId,$logType,$remark,$commentId=0,$content='',$progressId=0) {
        $logInfo=[
            'project_id' => $projectId,
            'task_id' => $taskId,
            'comment_id' => $commentId,
            'type' => $logType,//1指派任务及修改 2评论, 3改变进度状态的日志
            'remark' => $remark,
            'content'=>$content,
            'progress_id'=>$progressId,
            'admin_id' => ADMIN_ID,
            'create_time' => time(),
        ];
        return db('t_task_log')->insertGetId($logInfo);
    }

    /**
     * return json for data
     * @param   mixed $data   要返回的数据/出错消息
     * @param   int   $code   结果编辑码 ok/ok_online/e_args/e_op_fall/e_deny
     * @return void
     */
    public function return_json($code =200, $data = array()){
        $result['code'] = $code;
        $result['msg'] = $this->result_code_to_name($code);
        return $this->error($data);
        exit;
    }
    /**
     * code转中文
     * @param   int   $code   结果编辑码
     * @return $string
     */
    protected function result_code_to_name($code){
        switch ($code) {
            case 200:
                $r = '请求成功';
                break;
            case 'ok_online':
                $r = '操作成功,请等待...';
                break;
            case 'e_args':
                $r = '参数出错';
                break;
            case 'e_op_fall':
                $r = '操作失败';
                break;
            case 'e_deny':
                $r = '拒绝访问';
                break;
            default:
                $r = '请求失败';
                break;
        }
        return $r;
    }

    //审核任务
    public function checkTask(){
        $taskId=$this->request->param('task_id');
        $audit_status=$this->request->param('audit_status');
        $taskInfo=db('t_task')->where('id',$taskId)->find();
        $audit_users=db('t_project_user')->where([['project_id','eq',$taskInfo['project_id']],['type','eq',1]])->column("admin_id");
        if(empty($taskInfo)){
            $this->return_json(401,'不存在的任务id');
        }
        if(!in_array($audit_status,array(1,2))){
            $this->return_json(401,'错误的审批状态');
        }
        if($taskInfo['audit_status']!=0){
            //$this->return_json(401,'该任务已审核');
        }
        if(!in_array(ADMIN_ID,$audit_users)){
            $this->return_json(403,'你无权限审批该任务');
        }
        $audits=['','通过','驳回'];
        $savedata=['audit_status'=>$audit_status];
        $remark='审批了任务'.$audits[$audit_status];
        $progreccid=0;
        if($audit_status==1){
            if($taskInfo['status']<=1) $savedata['status']=1; //待审核状态时，审核同时变成未开始
            //$remark.='，任务状态已变更为未开始';
            $progreccid=1;
        }
        db('t_task')->where('id',$taskId)->update($savedata);
        $this->addLog($taskInfo['project_id'],$taskId, 3, $remark,0,'',$progreccid);
        $retData['task_id']=$taskId;
        $this->return_json(200,'success');
    }

    //获取任务的日志列表
    public function getTaskLogList($taskId){
        $systemUserKV = getSystemUserKV(null);
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        $logList=db('t_task_log')->where('task_id', $taskId)->page($page)->limit($limit)->order('create_time')->select();
        //$userPicKV=$this->getUserHeadpicList(array_column($logList,'admin_id'));
        foreach ($logList as $key => &$value) {
            $value['realname']= arrayGet($systemUserKV,$value['admin_id'],'');
            //$value['headimgurl']=isset($userPicKV[$value['admin_id']])?$userPicKV[$value['admin_id']] : '';
        }
        return $logList;
    }

    private function _getIdstrNames($strids,$idkeyArr){
        $search_marerialStatus=[];
        $stridsArr = explode(",", $strids);
        foreach ($stridsArr as $key => $value) {
            $search_marerialStatus[]= arrayGet($idkeyArr, $value, '');
        }
        $marerialStatus_str = implode(",", $search_marerialStatus);
        return $marerialStatus_str;
    }


    /**
     * 关注任务
     */
    public function attention() {
    	$taskId = $this->request->param('id/d', 0);

    	$tTaskLogService = new TTaskLogService();
    	$tTaskService = new TTaskService();
    	$tTaskAttentionService = new TTaskAttentionService();

    	$ttInfo = $tTaskService->getInfoById($taskId, 'id,project_id');
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}
    	$attentionId = $tTaskAttentionService->checkIsAttention($taskId);
    	if ($attentionId) {
			db('t_task_attention')->where('id', $attentionId)->delete();
			$isAttention = 0;
		} else {
			$insData = [
				'project_id' => $ttInfo['project_id'],
				'task_id' => $taskId,
				'admin_id' => ADMIN_ID,
				'create_time' => time(),
			];
			db('t_task_attention')->insertGetId($insData);
			$isAttention = 1;
		}
		return $this->Json(1, '', ['taskId' => $taskId, 'isAttention' => $isAttention]);
    }

    /**
     * 删除任务
     */
    public function del() {
    	$taskId = $this->request->param('id/d', 0);

    	$tTaskLogService = new TTaskLogService();
    	$tTaskService = new TTaskService();

    	$ttInfo = $tTaskService->getInfoById($taskId, 'id,name');
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}

    	try {
    		db()->startTrans();
    		// 入库
    		$upData = [
    			'status' => 0,
    			'update_time' => time(),
    		];
    		db('t_task')->where('id', $taskId)->update($upData);

    		// 记录操作日志
    		$tTaskLogService->addLog($taskId, 1, '删除了任务['.$ttInfo['name'].']');

    		db()->commit();

    		return $this->Json(1, '', ['taskId' => $taskId]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 任务流转
     */
    public function progress() {
    	$taskId = $this->request->param('id/d', 0);
    	$adminId = $this->request->param('admin_id/d', 0);
    	$assistAdminIds = $this->request->param('assist_admin_ids/a', []);
    	$remark = $this->request->param('remark/s', '');

    	$tTaskLogService = new TTaskLogService();
    	$tTaskService = new TTaskService();

    	$ttInfo = $tTaskService->getInfoById($taskId);
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}

    	try {
    		db()->startTrans();

    		// 判断当前负责人是否自己
    		if($tTaskService->getProgressLastAdminId($taskId) == $adminId) {
    			throw new \Exception('当前已是该用户负责');
    		}

    		$upData = [
    			'update_time' => time(),
    		];
    		// 追加参与人
    		$joinAdminIds = explode(',', arrayGet($ttInfo, 'join_admin_ids', ''));
    		if (!in_array($adminId, $joinAdminIds)) {
    			array_push($joinAdminIds, $adminId);
    			$upData['join_admin_ids'] = implode(',', $joinAdminIds);
    		}
    		db('t_task')->where('id', $ttInfo['id'])->update($upData);

    		$systemUserKV = getSystemUserKV(null);

    		// 入库
    		$insData = [
    			'project_id' => $ttInfo['project_id'],
    			'task_id' => $taskId,
    			'admin_id' => $adminId,
    			'assist_admin_ids' => implode(',', $assistAdminIds),
    			'remark' => $remark,
    			'create_time' => time(),
    			'update_time' => time(),
    		];
    		$progressId = db('t_task_progress')->insertGetId($insData);

    		// 记录操作日志
    		$tTaskLogService->addLog($taskId, 3, arrayGet($systemUserKV, ADMIN_ID, '') . '将任务['.$ttInfo['name'].']指派给 ' . arrayGet($systemUserKV, $adminId, ''));

    		db()->commit();

    		return $this->Json(1, '', ['taskId' => $taskId]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 修改任务状态
     */
    public function status() {
    	$taskId = $this->request->param('id/d', 0);
    	$status = $this->request->param('status/d', 0);

    	$tTaskLogService = new TTaskLogService();
    	$tTaskService = new TTaskService();

    	$ttInfo = $tTaskService->getInfoById($taskId, 'id,name');
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}

    	try {
    		db()->startTrans();
    		// 入库
    		$upData = [
    			'status' => $status,
    			'update_time' => time(),
    		];
            $taskInfo=db('t_task')->find($taskId);
    		db('t_task')->where('id', $taskId)->update($upData);
    		// 记录操作日志
    		//$tTaskLogService->addLog($taskId, 1, '修改了任务['.$ttInfo['name'].']状态为' . arrayGet(config('mimo.task_status'), $status, ''));

            //$this->addLog($ttInfo['project_id'],$ttInfo['id'], 2, '新增了任务评论',$commentId);
            $task_status=['未审批','未开始','进行中','已完成'];
            $remark='将任务移动到 '.$task_status[$status];
            $logid=$this->addLog($taskInfo['project_id'],$taskId, 3, $remark,0,'',$status);
            if(!empty($logid)){
                db('t_task_log')->where('id',$logid)->update(['progress_id'=>$status]); //设置进度值 以供统计
            }

    		db()->commit();

    		return $this->Json(1, '', ['taskId' => $taskId]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }
	/**
     * 增加评论
     */
	public function addComment() {
		$taskId = $this->request->param('id/d', 0);
		$systemUserService=new SystemUserService();
		$systemUserKV = getSystemUserKV(null);
    	$tProjectService = new TProjectService();
    	$tTaskService = new TTaskService();
		$tTaskLogService = new TTaskLogService();
		$ttInfo = $tTaskService->getInfoById($taskId);
		$systemUserVK = $systemUserService->getVKList(null);
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}
		if ($this->request->isPost()) {
    		$postData = $this->request->post();
    		$content = $this->request->param('content/s', '');
			$result = array(); 
			preg_match_all ("/&gt;@(.*)\&lt/U", $content, $result);			
			$atAdminIds=[];
			foreach ($result[1] as $key => $value) {
				$atAdminIds[]= arrayGet($systemUserVK, $value, '');
			}
			$atAdminIds = implode(",", $atAdminIds);
			//新增评论
			try {
    			db()->startTrans();
				$CommentData=[
					'project_id' => $ttInfo['project_id'],
					'task_id' => $ttInfo['id'],
					'content' => $content,
					'admin_id' => ADMIN_ID,
					'at_admin_ids'=>$atAdminIds,
					'create_time' => time(),
					'update_time' => time(),
				];
				$commentId = db('t_task_comment')->insertGetId($CommentData);
				//更新任务时间
				db('t_task')->where('id',$ttInfo['id'])->update(['update_time'=>time()]);
    			// 记录操作日志
    			//$tTaskLogService->addLog($commentId, 2, '新增了任务['.$ttInfo['name'].']的评论');
                $this->addLog($ttInfo['project_id'],$ttInfo['id'], 2, '新增了任务评论',$commentId,$content);
    			db()->commit();
    			return $this->Json(1,"操作成功");
    		} catch (\Exception $e) {
    			db()->rollback();
    			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    		}
		}
	}

    //导出任务列表
	public function exportTask(){
        $where[]=['t.status','<',99];
        $systemUserKV = getSystemUserKV(null);
        $tasklist=db('t_task t')
            ->join("t_project p", 'p.id = t.project_id','left')->field("t.*,p.name as projectname")->order('t.id desc')
            ->where($where)->select();
        foreach ($tasklist as $key=>&$v){
            $logList=db('t_task_log')->where('task_id', $v['id'])->order('create_time asc')->select();
            $v['checktime']=$v['actiontime']=$v['finishtime']='';
            foreach ($logList as $key => &$value) {
                if(strpos($value['remark'],'批了任务通过')!==false && $v['checktime']==''){
                    $v['checktime']=date("Y-m-d H:i",$value['create_time']);
                }
                if(strpos($value['remark'],'进行中')!==false && $v['actiontime']==''){
                    $v['actiontime']=date("Y-m-d H:i",$value['create_time']);
                }
                if(strpos($value['remark'],'已完成')!==false && $v['finishtime']==''){
                    $v['finishtime']=date("Y-m-d H:i",$value['create_time']);
                }
            }
            $v['create_time']=date("Y-m-d H:i",$v['create_time']);
            $v['adminname']= arrayGet($systemUserKV,$v['admin_id'],'');
            $v['actionuser']= arrayGet($systemUserKV,$v['execute_uid'],'');
            $result=explode(',',$v['join_admin_ids']);
            $atAdminIds=[];
            foreach ($result as $key => $value) {
                $atAdminIds[]= arrayGet($systemUserKV, $value, '');
            }
            $atAdminIds = implode(" , ", $atAdminIds);
            $v['join_admins']=$atAdminIds;
        }
        $assign = [
            'tasklist' => $tasklist
        ];
        return $this->assign($assign)->fetch();
    }
}